package com.travelation.persistence;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.travelation.Constants;
import com.travelation.model.Post;

public class PostsRetriever implements Retriever {

	// names of the tags
	static final String POSTID = "postID";
	static final String OWNERID = "ownerID";
	static final String TITLE = "title";
	static final String PRICE = "price";
	static final String IMAGEURL = "imageURL";
	static final String DESCRIPTION = "description";
	static final String ADDRESS = "address";
	static final String RENTCOUNT = "rentCount";
	static final String LOCATION = "location"; // geospatial key

	public ArrayList<Post> retrieve() {
		// /Log.d(Constants.LOG_TAG, "parse invoked");
		ArrayList<Post> posts = new ArrayList<Post>();
		MongoLabClient mongoClient = new MongoLabClient("zgdeals", "posts");
		try {
			Post currentPost = null;
			JSONArray jsons = mongoClient.findNear(0, 0, 1000);
			if (jsons != null) {
				for (int i = 0; i < jsons.length(); i++) {
					JSONObject element = jsons.getJSONObject(i);
					currentPost = new Post();
					currentPost.setAddress(element.getString(ADDRESS));
					currentPost.setConvertedCurrentPrice(element.getInt(PRICE));
					currentPost.setDesc(element.getString(DESCRIPTION));
					currentPost.setItemId(element.getLong(POSTID));
					currentPost.setOwnerId(element.getString(OWNERID));
					currentPost.setPicUrl(element.getString(IMAGEURL));
					currentPost.setPic175Url(element.getString(IMAGEURL));
					currentPost.setSmallPicUrl(element.getString(IMAGEURL));
					currentPost.setRentedCount(element.getInt(RENTCOUNT));
					currentPost.setTitle(element.getString(TITLE));
					posts.add(currentPost);
				}
			}
		} catch (Exception e) {
			Log.e(Constants.LOG_TAG, "Exception retrieving data", e);
			throw new RuntimeException(e);
		}
		return posts;
	}
}
